<?php

namespace App\Http\Services;

use App\Http\Model\ContentCheck;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\Friends;
use App\Http\Model\Hint;
use App\Http\Model\Medal;
use App\Http\Model\RoomUser;
use App\Http\Model\System;
use App\Http\Model\Trends;
use App\Http\Model\User;
use App\Lib\map;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Model\Mall;
use App\Http\Model\TrendsTopic;
use App\Http\Model\Room;
use App\Lib\Publisher;
use App\Http\Model\Nameplate;

/*动态service层*/

class TrendsServices extends CommonServices
{
    protected $user;
    protected $trends;
    protected $friends;
    protected $positionConf = 50000;//m 附近
    protected $timeConf = 3600 * 24 * 3;//second 最新
    protected $recommendTimeConf = 30 * 24 * 60 * 60; //30天以内
    private $model_financeuserwallet;
    protected $modelMedal;
    protected $trendsTopicModel;
    protected $roomModel;
    protected $contentCheckModel;
    protected $modelSystem;
    protected $nameplateModel;

    public function __construct()
    {
        parent::__construct();

        $this->user = new User();
        $this->trends = new Trends();
        $this->friends = new Friends();
        $this->model_financeuserwallet = new FinanceUserWallet();
        $this->modelMedal = new Medal();
        $this->trendsTopicModel = new TrendsTopic();
        $this->roomModel = new Room();
        $this->contentCheckModel = new ContentCheck();
        $this->modelSystem = new System();
        $this->nameplateModel = new Nameplate();
    }

    //动态列表 5=关注(好友) 10=最新
    public function listService($act_type, $page, $page_size, $lng, $lat ,$sex = 0)
    {
        $list = [];
        $user = $this->user->get_current_user();
        switch ($act_type) {
            case 2:
                $list = $this->getNearTimeList($page, $page_size, $lat, $lng);
                break;
            case 5:
                if(empty($sex)){
                    $last_select_gender = $this->trends->getLastSelectGender($user['user_id']);
                    if(empty($last_select_gender)){
                        $genders = !empty($user['gender']) && $user['gender'] ==2 ? array(1) : array(2);
                    }else{
                        $genders = $last_select_gender <3 ? array($last_select_gender) : array(0,1,2);
                    }
                }else{
                    $this->trends->setLastSelectGender($user['user_id'] ,$sex);
                    $genders = $sex == 3 ?  array(0,1,2) : array($sex);
                }
                $list = $this->getFollowCList($page, $page_size, $lat, $lng,$genders);
                break;
            case 10:
                $examine_switch = $this->modelSystem->getExamineSwitch('switch');

                if($examine_switch ==1){
                    $content_ids = $this->modelSystem->getExamineSwitch('trends');
                    $list = $this->trends->getTrendsByContentIds(explode(",",$content_ids));
                    $list = $this->makeDistance($list, $lat, $lng);
                    break;
                }

                if(empty($sex)){
                    $last_select_gender = $this->trends->getLastSelectGender($user['user_id']);
                    if(empty($last_select_gender)){
                        $genders = !empty($user['gender']) && $user['gender'] ==2 ? array(1) : array(2);
                    }else{
                        $genders = $last_select_gender <3 ? array($last_select_gender) : array(0,1,2);
                    }
                }else{
                    $this->trends->setLastSelectGender($user['user_id'] ,$sex);
                    $genders = $sex == 3 ?  array(0,1,2) : array($sex);
                }
                $list = $this->getAllTrendsList($page, $page_size, $lat, $lng ,$genders ,$user['user_id']);
                break;
            default:
                break;
        }

        $list = $this->trendsTopic($list);
        $list = $this->makeUserInfo($list ,in_array($act_type ,array(2,5,9,10)));
        $list = $this->countData($list);
        $list = $this->make_like($list);

        //2019-11-04需求
        /*
         * 增加评论列表 - 按评论点赞数排列
         * 增加评论数 comment_count 无变化
         * 增加点赞列表
         * 增加点赞数 like_count 无变化
         * */
        //获取评论列表
        $list = $this->getTrendCommentList($list);
        //获取点赞列表
        $list = $this->getTrendLikeList($list);


        //处理审核内容相关
        $list = $this->getContentCheckList($list);
        $default_select_gender =  $this->trends->getLastSelectGender($user['user_id']) ? $this->trends->getLastSelectGender($user['user_id']) : ($user['gender'] == 1 ? 2 : 1);

        return ['list' => $list, 'page_index' => $page, 'page_count' => count($list), 'page_size' => $page_size ,'last_gender'=> $default_select_gender ];
    }

    /**
     * 获取动态话题
     *
     * @param array $list 动态列表
     * @return array
     * */
    public function trendsTopic($list)
    {
        do {
            if (empty($list)) {
                break;
            }

            $contentIds = array_unique(array_column($list, 'content_id'));
            $getTrendsTopicDataByContentIds = $this->trendsTopicModel->getTrendsTopicDataByContentIds($contentIds);
            if (empty($getTrendsTopicDataByContentIds)) {
                foreach ($list as $key => $value) {
                    $list[$key]['topic'] = [];
                }
                break;
            }

            foreach ($list as $key => $value) {
                if (!isset($value['content_id']) or !array_key_exists($value['content_id'], $getTrendsTopicDataByContentIds)) {
                    $list[$key]['topic'] = [];
                    continue;
                }

                $list[$key]['topic'] = $getTrendsTopicDataByContentIds[$value['content_id']];
            }

        } while (false);

        return $list;
    }

    /**
     * 处理feed流点赞列表
     *
     * @param array $list 动态列表
     * @return array
     * */
    public function getTrendLikeList($list)
    {
        do {
            if (empty($list)) {
                break;
            }

            $uids = [];

            //获取点赞列表
            foreach ($list as $key => $value) {
                $list[$key]['like_list'] = $this->trends->getTrendLikeList($value['content_id'], 0, 4);
                //获取用户头像信息
                $uids = $list[$key]['like_list'] ? array_merge($uids, array_column($list[$key]['like_list'], "user_id")) : array_merge($uids,[]);

            }

            //整合UID列表
            $uids = array_values(array_unique($uids));
            $users = $this->user->get_users_by_ids($uids);

            //处理用户头像信息
            foreach ($list as $key => $value) {
                if ($list[$key]['like_list']) {
                    foreach ($list[$key]['like_list'] as $lk => $lv) {
                        $user_id = $lv['user_id'];
                        $findUser = array_values(array_filter($users, function ($param) use ($user_id) {
                            return $param['user_id'] == $user_id;
                        }));
                        $list[$key]['like_list'][$lk]['thumbnails'] = ($findUser && isset($findUser[0]) && isset($findUser[0]["thumbnails"]) && isset($findUser[0]["thumbnails"][0])) ? $findUser[0]["thumbnails"][0] : "";
                    }
                }
            }

        } while (false);

        return $list;
    }

    /**
     * 获取动态评论列表
     *
     * @param array $list 动态列表
     * @return array
     * */
    public function getTrendCommentList($list)
    {
        do {
            if (empty($list)) {
                break;
            }

            $uids = [];

            //获取评论列表
            foreach ($list as $key => $value) {
                //bywangxf:
                //8/10动态评论显示条数未正确显示
                //修改参数page_size控制
                $commentList = $this->trends->comments_list($value['content_id'], 0, 999);
                $list[$key]['comment_list'] = ($commentList && isset($commentList['list'])) ? $commentList['list'] : [];
                $uids = ($commentList && isset($commentList['list'])) ? array_merge($uids, array_column($commentList['list'], "user_id")) : array_merge($uids, []);
            }
            //整合UID列表
            $uids = array_values(array_unique($uids));
            $users = $this->user->get_users_by_ids($uids);
            //获取评论列表用户信息
            foreach ($list as $key => $value) {
                if ($list[$key]['comment_list']) {
                    foreach ($list[$key]['comment_list'] as $lk => $lv) {

                        $user_id = $lv['user_id'];
                        $findUser = array_values(array_filter($users, function ($param) use ($user_id) {
                            return $param['user_id'] == $user_id;
                        }));
                        $list[$key]['comment_list'][$lk]['nickname'] = ($findUser && isset($findUser[0]) && isset($findUser[0]["nickname"])) ? $findUser[0]["nickname"] : "";
                    }

                }
            }
        } while (false);

        return $list;
    }


    //发布动态
    public function releaseService($type, $content, $resource_urls, $position_name, $lng, $lat, $cover, $resource_time, $topicIds = '' ,$work_id =0, $longImg = 0, &$curUserInfo = null, $handbookId=0)
    {

        $userInfo = $curUserInfo =  $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }

        // todo 不上传经纬度时，根据当前客户端的ip地址获取经纬度
        if (!$lat && !$lng) {
            $map = new map();
            $map = $map->get_location(get_remote_addr());
            $lng = $map['lng'];
            $lat = $map['lat'];
        }
        // todo end

        if (empty($content)) {
            $content = "";
        }

        $images = [];
        foreach ($resource_urls as $k => $v) {
            $tempArr = parse_url($v);
            if (isset($tempArr['path'])) {
                $images[] = $tempArr['path'];
            }
        }
        $covers = [];
        $pic_host = parse_url(getPicDomain(), PHP_URL_HOST);
        foreach ($cover as $k => $v) {
            $tempArr = parse_url($v);
            if (isset($tempArr['path']) && isset($tempArr['host'])) {
                if ($pic_host == $tempArr['host']) {
                    $covers[] = $tempArr['path'];
                } else {
                    $covers[] = $v;
                }
            }
        }
        $releaseData = [
            'c_type' => $type,
            'm_type' => 1,
            'user_id' => $userInfo['user_id'],
            'c_content' => $content,
            'create_timestamp' => time(),
            'position_name' => $position_name,
            'p_lng' => $lng,
            'p_lat' => $lat,
            'type' =>3 ,//默认所有人可见
            'long_img' => $longImg
        ];
        if(!empty($handbookId)){
            $releaseData['handbook_id'] = $handbookId;
        }
        if ($type == 1) {
        } elseif ($type == 2 || $type == 7 || $type == 8) {
            $releaseData['c_imgs'] = implode(',', $images);
        } elseif ($type == 3) {
            $releaseData['c_video'] = isset($images[0]) ? $images[0] : '';
            $releaseData['c_cover'] = isset($covers[0]) ? $covers[0] : '';
        } elseif ($type == 4) {
            $releaseData['c_voice'] = isset($images[0]) ? $images[0] : '';
            $releaseData['c_cover'] = isset($covers[0]) ? $covers[0] : '';
            $releaseData['c_voice_time'] = $resource_time;
        } elseif ($type == 5) {// CP 喜结良缘

        } else if($type == 6){
            $releaseData['c_voice'] = isset($images[0]) ? $images[0] : '';
            $releaseData['c_voice_time'] = $resource_time;
        }
        else {
            return false;
        }

        // 动态发布用户性别
        if (in_array($userInfo['gender'], [1, 2])) {
            $releaseData['gender_type'] = $userInfo['gender'];
        }

        // 读取动态审核是否开启
        $trendsAuditSwitch = $this->trends->trendsAuditSwitch();
        switch ($trendsAuditSwitch) {
            case 0:// 关闭则不需要审核
                $releaseData['state'] = 1;// 审核通过
                break;
            case 1:// 开启则需要审核
                $releaseData['state'] = 0;// 待审核
                break;
        }

        $list = $this->trends->trends_add($releaseData);

        // 话题参数创建
        $contentId = $list[0]['content_id'] ?? 0;
        if (!empty($topicIds) and $contentId > 0) {
            $topicIdArray = array_unique(array_filter(explode(',', $topicIds)));
            if (!empty($topicIdArray)) {
                // 根据话题ID获取动态话题
                $getTrendsTopicById = $this->trendsTopicModel->getTrendsTopicById($topicIdArray);
                if(!empty($getTrendsTopicById)){
                    $insertBatchData = [];
                    foreach ($getTrendsTopicById as $value) {
                        $insertBatchData[] = ['topic_id' => $value['topic_id'], 'content_id' => $contentId, 'created_at' => time()];
                    }

                    $this->trendsTopicModel->CUDTrendsTopicJoin($insertBatchData, 'insertBatch');
                }
            }
        }

        $list = $this->makeUserInfo($list);
        $list = $this->countData($list);
        $list = $this->make_like($list);
        if (empty($list)) {
            return null;
        }
        return $list[0];

    }

    //删除动态
    public function deleteService($contentId)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }

        $ret = $this->trends->trends_del($userInfo['user_id'], $contentId);

        // 删除话题参与的动态数据
        if ($ret) {
            $this->trendsTopicModel->CUDTrendsTopicJoin([], 'delete', $contentId);
        }

        return $ret;
    }

    //删除回复
    public function deleteReplyService($reply_id)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        return $this->trends->trends_reply_del($userInfo['user_id'], $reply_id);
    }

    //删除评论
    public function deleteCommentService($comment_id)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        $comment = $this->trends->get_comment($comment_id);
        if (empty($comment)){
            return false;
        }
        $content = $this->trends->trend($comment['content_id']);
        if (empty($content)){
            return false;
        }
        if ($userInfo['user_id'] != $content['user_id'] && $userInfo['user_id'] != $comment['user_id']){
            return false;
        }
        return $this->trends->trends_comment_del( $comment_id);
    }


    //点赞or取消点赞
    public function likeService($actType, $contentId, &$cur_user_id)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        $cur_user_id = $userInfo['user_id'];
        return $this->trends->trends_like($userInfo['user_id'], $contentId, $actType);
    }

    //评论点赞or取消点赞
    public function likeCommentService($actType, $commentId)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        return $this->trends->trends_comment_like($userInfo['user_id'], $commentId, $actType);
    }

    /**
     * 回复点赞
     * @param $actType
     * @param $replyId
     * @return bool
     */
    public function likeReplyService($actType, $replyId)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        return $this->trends->trends_reply_like($userInfo['user_id'], $replyId, $actType);
    }

    //阅读
    public function readService($contentId, &$cur_user_id)
    {
        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            $cur_user_id = $userInfo['user_id'];
            return $this->trends->trends_read($contentId, $userId);
        }
        return true;
    }

    //转发
    public function relayService($contentId)
    {
        $userInfo = $this->user->get_current_user();
        if (!empty($userInfo)) {
            $userId = $userInfo['user_id'];
            return $this->trends->trends_relay($contentId, $userId);
        }
        return true;
    }

    //发布评论
    public function commentService($content_id, $comment_text, $voice_resource, $lng, $lat, $voice_time, &$cur_user_id, string $comment_img)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }

        // if (empty($userInfo['active_certify'])){
        //     return Hint::USER_NOT_CERTIFICATION;
        // }

        // 用户被屏蔽
        if ($this->trends->isBlock($content_id, $userInfo['user_id'])){
            return Hint::AUTH_ERROR;
        }

        $content = $this->trends->trend($content_id);
        if (empty($content)){
            return false;
        }
        $userFriends = new Friends();
        if ($userFriends->get_block_exist($content['user_id'], $userInfo['user_id'])){
            return Hint::AUTH_ERROR;
        }

        $userId = $userInfo['user_id'];
        $cur_user_id = $userInfo['user_id'];
        $time = time();
        $tempArr = parse_url($voice_resource);

        if (empty($voice_time)) {
            $voice_time = 0;
        }

        $data = ['content_id' => $content_id, 'user_id' => $userId, 'comment_text' => $comment_text, 'comment_voice' => isset($tempArr['path']) ? $tempArr['path'] : '', 'create_timestamp' => $time, 'p_lng' => $lng, 'p_lat' => $lat, 'comment_voice_time' => $voice_time];
        if (!empty($comment_img)) {
            $data = array_merge($data, ['comment_img' => $comment_img]);
        }
        $this->trends->trends_comment_count($content_id);
        $commentsList = $this->trends->trends_comment($data);

        $ids = array_unique($commentsList['user_ids']);
        sort($ids);
        $temp = [];
        $temp1 = [];
        $medalData = [];
        if (!empty($ids)) {
            $users = $this->user->get_users_by_ids($ids);
            if (!empty($users)) {
                foreach ($users as $k => $v) {
                    $temp[$v['user_id']] = $v;
                }
            }
            $wallets = $this->model_financeuserwallet->get_wallets($ids);
            if (!empty($wallets)) {
                foreach ($wallets as $k => $v) {
                    $temp1[$v['user_id']] = $v;
                }
            }
            $medalArr = $this->modelMedal->getMedalUserListCache($ids, false);
            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
        }

        if (!empty($commentsList['list'])) {
            foreach ($commentsList['list'] as $k => $v) {
                $commentsList['list'][$k]['user'] = $temp[$v['user_id']];
                $commentsList['list'][$k]['user']['wealth_balance'] = $temp1[$v['user_id']]['wealth_balance'];
                $commentsList['list'][$k]['user']['charm_balance'] = $temp1[$v['user_id']]['charm_balance'];
                $commentsList['list'][$k]['user']['kk_balance'] = $temp1[$v['user_id']]['kk_balance'];
                $commentsList['list'][$k]['user']['reputation_balance'] = $temp1[$v['user_id']]['reputation_balance'];
                $commentsList['list'][$k]['user']['celebrity_balance'] = $temp1[$v['user_id']]['celebrity_balance'];

                if (array_key_exists(intval($v['user_id']), $medalData)){
                    $commentsList['list'][$k]['user']['medal'] = $medalData[intval($v['user_id'])];
                }
                else{
                    $commentsList['list'][$k]['user']['medal'] = [];
                }

            }
        }
        $commentsList = $this->makeCommentDistance($commentsList, $lat, $lng);
        $commentsList['list'] = $this->make_comment_like($commentsList['list']);
        return $commentsList['list'][0];

    }

    //回复评论
    public function replyService($reply_type, $comment_id, $reply_id, $reply_text, $voice_resource, $content_id, $lng, $lat, $voice_time, $reply_img)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }

        if (empty($userInfo['active_certify'])){
            return Hint::USER_NOT_CERTIFICATION;
        }

        // 用户被屏蔽
        if ($this->trends->isBlock($content_id, $userInfo['user_id'])){
            return Hint::AUTH_ERROR;
        }

        $content = $this->trends->trend($content_id);
        if (empty($content)){
            return false;
        }
        $userFriends = new Friends();
        if ($userFriends->get_block_exist($content['user_id'], $userInfo['user_id'])){
            return Hint::AUTH_ERROR;
        }


        $userId = $userInfo['user_id'];
        $time = time();
        $tempArr = parse_url($voice_resource);
        if ($reply_type == 1) {
            $user = $this->trends->get_comment($comment_id);
            if (empty($user)) {
                return false;
            }
            $toUserId = $user['user_id'];
        } else {
            $user = $this->trends->get_reply($reply_id);
            if (empty($user)) {
                return false;
            }
            $toUserId = $user['from_user_id'];
        }
        $data = ['content_id' => $content_id, 'comment_id' => $comment_id, 'reply_id' => $reply_id, 'reply_type' => $reply_type, 'reply_voice' => isset($tempArr['path']) ? $tempArr['path'] : '', 'from_user_id' => $userId, 'to_user_id' => $toUserId, 'reply_content' => $reply_text, 'create_timestamp' => $time, 'p_lng' => $lng, 'p_lat' => $lat, 'reply_voice_time' => $voice_time];
        if (!empty($reply_img)) {
            $data = array_merge($data, ['reply_img' => $reply_img]);
        }
        $this->trends->trends_comment_count($content_id);
        $replyList = $this->trends->trends_reply($data);

        $ids = array_unique(array_merge($replyList['f_user_ids'], $replyList['t_user_ids']));
        sort($ids);
        $temp = $temp1 = [];
        $medalData = [];
        if (!empty($ids)) {
            $users = $this->user->get_users_by_ids($ids);
            if (!empty($users)) {
                foreach ($users as $k => $v) {
                    $temp[$v['user_id']] = $v;
                }
            }
            $wallets = $this->model_financeuserwallet->get_wallets($ids);
            if (!empty($wallets)) {
                foreach ($wallets as $k => $v) {
                    $temp1[$v['user_id']] = $v;
                }
            }
            $medalArr = $this->modelMedal->getMedalUserListCache($ids, false);
            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
        }

        if (!empty($replyList['list'])) {
            foreach ($replyList['list'] as $k => $v) {
                $replyList['list'][$k]['from_user'] = $temp[$v['from_user_id']];
                $replyList['list'][$k]['to_user'] = $temp[$v['to_user_id']];
                $replyList['list'][$k]['from_user']['wealth_balance'] = $temp1[$v['from_user_id']]['wealth_balance'];
                $replyList['list'][$k]['from_user']['charm_balance'] = $temp1[$v['from_user_id']]['charm_balance'];
                $replyList['list'][$k]['from_user']['kk_balance'] = $temp1[$v['from_user_id']]['kk_balance'];
                $replyList['list'][$k]['from_user']['reputation_balance'] = $temp1[$v['from_user_id']]['reputation_balance'];
                $replyList['list'][$k]['from_user']['celebrity_balance'] = $temp1[$v['from_user_id']]['celebrity_balance'];
                if (array_key_exists(intval($v['from_user_id']), $medalData)){
                    $replyList['list'][$k]['from_user']['medal'] = $medalData[intval($v['from_user_id'])];
                }
                else{
                    $replyList['list'][$k]['from_user']['medal'] = [];
                }
            }
        }

        $replyList['list'] = $this->make_reply_like($replyList['list']);

        $replyList = $this->makeReplyDistance($replyList, $lat, $lng);

        return $replyList['list'][0];
    }

    //评论列表
    public function commentListService($contentId, $page, $page_size, $lng, $lat)
    {
        $commentsList = $this->trends->comments_list($contentId, $page, $page_size);
        $ids = array_unique($commentsList['user_ids']);
        sort($ids);
        $temp = [];
        $temp1 = [];
        if (!empty($ids)) {
            $users = $this->user->get_users_by_ids($ids);
            if (!empty($users)) {
                foreach ($users as $k => $v) {
                    $temp[$v['user_id']] = $v;
                }
            }
            $wallets = $this->model_financeuserwallet->get_wallets($ids);
            if (!empty($wallets)) {
                foreach ($wallets as $k => $v) {
                    $temp1[$v['user_id']] = $v;
                }
            }
        }

        if (!empty($commentsList['list'])) {
            // 查询用户勋章
            $userKeyIdArray = array_column($commentsList['list'],'user_id','user_id');
            $userIdArray = array_column($commentsList['list'],'user_id');
            $medal = $this->modelMedal->getMedalUserListCache($userIdArray,false);

            foreach ($commentsList['list'] as $k => $v) {
                $commentsList['list'][$k]['user'] = $temp[$v['user_id']];
                $commentsList['list'][$k]['user']['wealth_balance'] = $temp1[$v['user_id']]['wealth_balance'];

                $commentsList['list'][$k]['user']['medal'] = [];
                if(!empty($medal) and array_key_exists($v['user_id'],$userKeyIdArray)) {
                    $userIdIndex = array_search($v['user_id'], $userIdArray);
                    $commentsList['list'][$k]['user']['medal'] = $medal[$userIdIndex];
                }
            }
        }
        $commentsList = $this->makeCommentDistance($commentsList, $lat, $lng);
        $commentsList['list'] = $this->make_comment_like($commentsList['list']);

        //内容处理
        $contentCheckList[0]['comment_list'] = $commentsList['list'];
        $contentCheckResult = $this->getContentCheckList($contentCheckList);
        $commentsList['list'] = $contentCheckResult ? $contentCheckResult[0]["comment_list"] : [];

        return ['list' => $commentsList['list'], 'page_index' => $page, 'page_count' => count($commentsList['list']), 'page_size' => $page_size];
    }

    //回复列表
    public function replyListService($commentId, $page, $page_size, $lng, $lat)
    {
        $replyList = $this->trends->replys_list($commentId, $page, $page_size);
        $ids = array_unique(array_merge($replyList['f_user_ids'], $replyList['t_user_ids']));
        sort($ids);

        $temp = $temp1 = [];
        $medalData = [];
        if (!empty($ids)) {
            $users = $this->user->get_users_by_ids($ids);
            if (!empty($users)) {
                foreach ($users as $k => $v) {
                    $temp[$v['user_id']] = $v;
                }
            }
            $wallets = $this->model_financeuserwallet->get_wallets($ids);
            if (!empty($wallets)) {
                foreach ($wallets as $k => $v) {
                    $temp1[$v['user_id']] = $v;
                }
            }
            $medalArr = $this->modelMedal->getMedalUserListCache($ids, false);

            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
        }

        if (!empty($replyList['list'])) {
            foreach ($replyList['list'] as $k => $v) {
                $replyList['list'][$k]['from_user'] = $temp[$v['from_user_id']];
                $replyList['list'][$k]['to_user'] = $temp[$v['to_user_id']];
                $replyList['list'][$k]['from_user']['wealth_balance'] = $temp1[$v['from_user_id']]['wealth_balance'];
                $replyList['list'][$k]['from_user']['reputation_balance'] = $temp1[$v['from_user_id']]['reputation_balance'];
                $replyList['list'][$k]['from_user']['celebrity_balance'] = $temp1[$v['from_user_id']]['celebrity_balance'];
                if (array_key_exists(intval($v['from_user_id']), $medalData)){
                    $replyList['list'][$k]['from_user']['medal'] = $medalData[intval($v['from_user_id'])];
                }
                else{
                    $replyList['list'][$k]['from_user']['medal'] = [];
                }

            }
        }
        $replyList['list'] = $this->make_reply_like($replyList['list']);
        $replyList = $this->makeReplyDistance($replyList, $lat, $lng);

        //内容处理
        $contentCheckList[0]['comment_list'] = $replyList['list'];
        $contentCheckResult = $this->getContentCheckList($contentCheckList, 2);
        $replyList['list'] = $contentCheckResult ? $contentCheckResult[0]["comment_list"] : [];

        return ['list' => $replyList['list'], 'page_index' => $page, 'page_count' => count($replyList['list']), 'page_size' => $page_size];
    }


    /**
     * 获取单独动态内容
     * @param $content_id
     * @param $lat
     * @param $lng
     * @return null
     */
    public function get_trends($content_id, $lat, $lng)
    {
        $data = [];
        $content = $this->trends->trend($content_id);
        if (empty($content)) {
            return null;
        }
        $data[] = $content;
        $result = $this->trendsTopic($data);
        $result = $this->makeDistance($result, $lat, $lng);
        $result = $this->makeUserInfo($result);
        $result = $this->countData($result);
        $result = $this->make_like($result);
        return $result[0];
    }


    /**
     * 获取用户动态
     * @param $page
     * @param $page_size
     * @param $user_id
     * @param $lat
     * @param $lng
     * @return null
     */
    public function get_user_trends($page, $page_size, $user_id, $lat, $lng)
    {
        // 获取当前登录用户
        $currUser = $this->user->get_current_user();

        $data = $this->trends->user_trends_list($page, $page_size, $user_id, $currUser['user_id'] ?? 0 ,true);
        if (empty($user_id)) {
            return [];
        }

        $result = $this->makeDistance($data, $lat, $lng);
        $result = $this->makeUserInfo($result);
        $result = $this->countData($result);
        $result = $this->make_like($result);
        $result = $this->trendsTopic($result);

        return ['list' => $result, 'page_index' => $page, 'page_count' => count($result), 'page_size' => $page_size];

    }

    //获取推荐列表
    private function getRecommendList($page, $page_size, $lat, $lng)
    {
        $min_time = time() - $this->recommendTimeConf; //user
        $ids = $this->trends->trends_recomment_items($min_time);
        if (empty($ids)) {
            return [];
        }

        // 获取当前登录用户
        $currUser = $this->user->get_current_user();
        $list = $this->trends->trends_recommend_list($page, $page_size, $min_time, $ids, $currUser['user_id'] ?? 0);
        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取最新列表
    private function getNearTimeList($page, $page_size, $lat, $lng)
    {
        // 获取当前登录用户
        $currUser = $this->user->get_current_user();

        $minTime = time() - $this->timeConf;
        if($page_size==5){
            $ctype=3;
        }
        $list = $this->trends->trends_new_list($ctype,$page, $page_size, $minTime,$currUser['user_id'] ?? 0 ,true);
        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取附近列表
    private function getNearDistanceList($page, $page_size, $lat, $lng)
    {
        // todo 不上传经纬度时，根据当前客户端的ip地址获取经纬度
        if (!$lat && !$lng) {
            $map = new map();
            $map = $map->get_location(get_remote_addr());
            $lng = $map['lng'];
            $lat = $map['lat'];
        }
        // todo end

        // 获取当前登录用户
        $currUser = $this->user->get_current_user();

        $positionRange = calcScope($lat, $lng, $this->positionConf);
        $list = $this->trends->trends_near_list($page, $page_size, $positionRange,$currUser['user_id'] ?? 0);
        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取声控列表
    private function getVoiceList($page, $page_size, $lat, $lng)
    {
        // 获取当前登录用户
        $currUser = $this->user->get_current_user();

        $list = $this->trends->trends_voice_list($page, $page_size,$currUser['user_id'] ?? 0);
        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取关注列表
    private function getFollowCList($page, $page_size, $lat, $lng ,$genders)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        $followArr = $this->friends->get_follows($userInfo['user_id']);
        $ids = [];
        $list = [];
        foreach ($followArr as $k => $v) {
            $ids[] = $v['user_id'];
        }
        if (!empty($ids)) {
            $list = $this->trends->trends_follow_list($page, $page_size, $ids ,$genders,true);
        }

        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取粉丝发布列表
    private function getFansCList($page, $page_size, $lat, $lng)
    {
        $userInfo = $this->user->get_current_user();
        if (empty($userInfo)) {
            return false;
        }
        $fansArr = $this->friends->get_fans($userInfo['user_id']);
        $ids = [];
        $list = [];
        foreach ($fansArr as $k => $v) {
            $ids[] = $v['user_id'];
        }
        if (!empty($ids)) {
            $list = $this->trends->trends_fans_list($page, $page_size, $ids);
        }

        $result = $this->makeDistance($list, $lat, $lng);
        return $result;
    }

    //获取男女类型发布动态列表
    private function getGenderTypeList($page, $page_size, $lat, $lng, $genderType)
    {
        $list = $this->trends->trendsGenderTypeList($page, $page_size, $genderType);
        return $this->makeDistance($list, $lat, $lng);
    }
    //获取精选类型发布动态列表
    private function getDelicateTypeList($page, $page_size, $lat, $lng ,$gender = 2 ,$user_id=0)
    {
        $list = $this->trends->getDelicateTypeList($page, $page_size ,$gender ,$user_id,true);
        return $this->makeDistance($list, $lat, $lng);
    }

    /**动态-全部
     * @param $page
     * @param $page_size
     * @param $lat
     * @param $lng
     * @param $genders
     * @param int $user_id
     * @return mixed
     */
    public function getAllTrendsList($page, $page_size, $lat, $lng ,$genders ,$user_id=0){
        $followArr = $this->friends->get_follows($user_id);
        $user_ids = [];
        foreach ($followArr as $k => $v) {
            $user_ids[] = $v['user_id'];
        }
        $user_ids[] = $user_id;
        $list = $this->trends->getAllTrendsList($page, $page_size ,$genders ,$user_ids,true);
        return $this->makeDistance($list, $lat, $lng);
    }
    //动态距离信息
    public function makeDistance($list, $lat, $lng)
    {
        if (!empty($list)) {
            if ($lat && $lng) {
                foreach ($list as $k => $v) {
                    if ($v['position_name'] && $v['p_lat'] && $v['p_lng']) { //发布位置完善
                        if ($v['p_lat'] == 0 || $v['p_lng'] == 0 || $lat == 0 || $lng == 0){
                            $list[$k]['distance'] = '';
                            unset($list[$k]['p_lat']);
                            unset($list[$k]['p_lng']);
                            continue;
                        }
                        $distance = calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']);
                        if ($distance) {
                            $list[$k]['distance'] = sprintf("%.2f", calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']));
                        } else {
                            $list[$k]['distance'] = '0';
                        }
                    }
                    unset($list[$k]['p_lat']);
                    unset($list[$k]['p_lng']);
                }
            }
        }
        return $list;
    }

    //评论距离信息
    public function makeCommentDistance($list, $lat, $lng)
    {
        if (!empty($list['list'])) {
            if ($lat && $lng) {
                foreach ($list['list'] as $k => $v) {
                    if ($v['p_lat'] && $v['p_lng']) { //发布位置完善
                        if ($v['p_lat'] == 0 || $v['p_lng'] == 0 || $lat == 0 || $lng == 0){
                            $list['list'][$k]['distance'] = '';
                            unset($list['list'][$k]['p_lat']);
                            unset($list['list'][$k]['p_lng']);
                            continue;
                        }
                        $distance = calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']);
                        if ($distance) {
                            $list['list'][$k]['distance'] = sprintf("%.2f", calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']));
                        } else {
                            $list['list'][$k]['distance'] = '0';
                        }
                    }
                    unset($list['list'][$k]['p_lat']);
                    unset($list['list'][$k]['p_lng']);
                }
            }
        }
        return $list;
    }

    //回复距离计算
    public function makeReplyDistance($list, $lat, $lng)
    {
        if (!empty($list['list'])) {
            if ($lat && $lng) {
                foreach ($list['list'] as $k => $v) {
                    if ($v['p_lat'] && $v['p_lng']) { //发布位置完善
                        if ($v['p_lat'] == 0 || $v['p_lng'] == 0 || $lat == 0 || $lng == 0){
                            $list['list'][$k]['distance'] = '';
                            unset($list['list'][$k]['p_lat']);
                            unset($list['list'][$k]['p_lng']);
                            continue;
                        }
                        $distance = calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']);
                        if ($distance) {
                            $list['list'][$k]['distance'] = sprintf("%.2f", calcDistance($lat, $lng, $v['p_lat'], $v['p_lng']));
                        } else {
                            $list['list'][$k]['distance'] = '0';
                        }
                    }
                    unset($list['list'][$k]['p_lat']);
                    unset($list['list'][$k]['p_lng']);
                }
            }
        }
        return $list;
    }

    //用户信息
    private function makeUserInfo($list ,$room_info = false)
    {
        $modelRoomUser = new RoomUser();
        $modelRoom = new Room();

        $tempIds = [];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $tempIds[] = $v['user_id'];
            }
        }
        $ids = array_unique($tempIds);
        sort($ids);
        $temp = [];
        $temp1 = [];
        $medalData = [];
        $mallModel = new Mall();
        if (!empty($ids)) {
            $users = $this->user->get_users_by_ids($ids);
            if (!empty($users)) {
                foreach ($users as $k => $v) {
                    $temp[$v['user_id']] = $v;
                }
            }
            $wallets = $this->model_financeuserwallet->get_wallets($ids);
            if (!empty($wallets)) {
                foreach ($wallets as $k => $v) {
                    $temp1[$v['user_id']] = $v;
                }
            }
            $medalArr = $this->modelMedal->getMedalUserListCache($ids, false);
            foreach ($medalArr as $val){
                if(empty($val)){
                    continue;
                }
                $medalData[$val[0]['user_id']] = $val;
            }
        }

        if (!empty($list)) {
            $cur_user = $this->user->get_current_user();
            foreach ($list as $k => $v) {
                $list[$k]['user'] = $temp[$v['user_id']];
                $list[$k]['user']['wealth_balance'] = $temp1[$v['user_id']]['wealth_balance'];
                $list[$k]['user']['charm_balance'] = $temp1[$v['user_id']]['charm_balance'];
                $list[$k]['user']['kk_balance'] = $temp1[$v['user_id']]['kk_balance'];
                $list[$k]['user']['reputation_balance'] = $temp1[$v['user_id']]['reputation_balance'];
                $list[$k]['user']['celebrity_balance'] = $temp1[$v['user_id']]['celebrity_balance'];
                $list[$k]['user']['is_follow'] = false;
                if (array_key_exists(intval($v['user_id']), $medalData)){
                    $list[$k]['user']['medal'] = $medalData[intval($v['user_id'])];
                }
                else{
                    $list[$k]['user']['medal'] = [];
                }


                if (!empty($cur_user)){
                    $list[$k]['user']['is_follow'] = $this->friends->get_follow_exist($cur_user['user_id'], $v['user_id']);
                }

                //增加是否在房间内的状态
                if($room_info){
                    $list[$k]['user']['is_room'] = 0;
                    $list[$k]['user']['room_id'] = 0;
                    $list[$k]['user']['model_str'] = '';
                    $userCurRoom = $modelRoomUser->get_user_cur_room($v['user_id']);
                    if($userCurRoom){
                        $list[$k]['user']['is_room'] = 1;
                        $list[$k]['user']['room_id'] = $userCurRoom;
                        $room_ids[] = $userCurRoom;
                    }
                }
                $attires = $mallModel->getGoodsAttire($v['user_id']);
                $list[$k]['user']['attires'] = $attires ?: [];

                //用户铭牌
                $list[$k]['user']['userNameplate'] = $this->nameplateModel->getNameplateByUserId($list[$k]['user']['user_id']);
            }
            if($room_info && isset($room_ids)){
                $roomData = $modelRoom->get_rooms_by_ids($room_ids);
                foreach ($list as $k=>$v){
                    $roomId = $v['user']['room_id'];
                    if(!empty($roomId)){
                        $filterRoomData = array_values(array_filter($roomData, function ($param) use ($roomId) {
                            return $roomId == $param['room_id'];
                        }));
                        $list[$k]['user']['model_str'] = $filterRoomData && $filterRoomData[0] && isset($filterRoomData[0]['model_str']) ? $filterRoomData[0]['model_str'] : "";
                    }
                }
            }
        }
        return $list;
    }

    /**
     * 添加动态是否点赞
     * @param $list
     * @return mixed
     */
    private function make_like($list)
    {
        $cur_user = $this->user->get_current_user();
        foreach ($list as $k => $v) {
            $list[$k]['is_like'] = false;
            if (!empty($cur_user)) {
                $list[$k]['is_like'] = $this->trends->trends_like_exist($cur_user['user_id'], $v['content_id']);
            }
        }
        return $list;

    }

    /**
     * 添加评论是否点赞
     * @param $list
     * @return mixed
     */
    private function make_comment_like($list)
    {
        $cur_user = $this->user->get_current_user();
        foreach ($list as $k => $v) {
            $list[$k]['is_like'] = false;
            if (!empty($cur_user)) {
                $list[$k]['is_like'] = $this->trends->trends_comment_like_exist($cur_user['user_id'], $v['comment_id']);
            }
        }
        return $list;
    }


    /**
     * 添加评论是否点赞
     * @param $list
     * @return mixed
     */
    private function make_reply_like($list)
    {
        $cur_user = $this->user->get_current_user();
        foreach ($list as $k => $v) {
            $list[$k]['is_like'] = false;
            if (!empty($cur_user)) {
                $list[$k]['is_like'] = $this->trends->trends_reply_like_exist($cur_user['user_id'], $v['reply_id']);
            }
        }
        return $list;
    }

    //统计信息
    private function countData($list)
    {
        $cur_user = $this->user->get_current_user();
        $ids = [];
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $ids[] = $v['content_id'];
            }
        }
        $temp = [];
        if (!empty($ids)) {
            $countData = $this->trends->trends_count($ids);
            if (!empty($countData)) {
                foreach ($countData as $k => $v) {
                    $temp[$v['content_id']] = $v;
                }
            }
        }
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['read_count'] = isset($temp[$v['content_id']]['read_count']) ? $temp[$v['content_id']]['read_count'] : 0;
                $list[$k]['comment_count'] = isset($temp[$v['content_id']]['comment_count']) ? $temp[$v['content_id']]['comment_count'] : 0;
                $list[$k]['like_count'] = isset($temp[$v['content_id']]['like_count']) ? $temp[$v['content_id']]['like_count'] : 0;
                $list[$k]['share_count'] = 0;
            }
        }
        return $list;
    }


    /**
     * 屏蔽用户
     * @param $contentId
     * @param $blockUserId
     */
    public function blockUser($contentId, $blockUserId){
        $cur_user = $this->user->get_current_user();
        if (empty($cur_user)){
            return false;
        }
        $content = $this->trends->trend($contentId);
        if (empty($content)){
            return false;
        }
        if ($cur_user['user_id'] != $content['user_id']){
            return false;
        }
        $this->trends->blockUser($contentId, $blockUserId);
        return true;
    }


    ################# 后台调用 ##########################################

    /**
     * 动态内容更新
     * */
    public function trendsUpdate()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('content_id', '内容ID', 'int', true, '内容ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $contentId = $this->requestData['content_id'];

                $ret = $this->trends->singleUpdate(['content_id' => $contentId], ['is_delete' => 1]);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '动态内容更新' . Hint::getErrCodeMsg($code);
                    break;
                }

                // 删除话题参与的动态数据
                $this->trendsTopicModel->CUDTrendsTopicJoin([], 'delete', $contentId);
                $this->trends->trendsRemoveRecommend($contentId);

                $data['content_id'] = intval($contentId);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 删除评论
     * */
    public function commentDel()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            try {
                $this->I('comment_id', '', 'int', true, '内容ID不能为空');

                $variables = [];
                $checkParams = $this->check($this->requestData, $variables); //校验数据
                extract($checkParams);
                if ($code !== Hint::SUCCESS) {
                    break;
                }
                extract($variables); //数组参数化

                $comment_id = $this->requestData['comment_id'];
                $this->trends->trends_comment_del( $comment_id);

            } catch (\Exception $e) {
                $code = Hint::ERR_SYS_FAIL;
                $msg = 'message：' . $e->getMessage() . '，line：' . $e->getLine();
                break;
            }
        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 动态审核开关
     * */
    public function trendsAuditSwitch()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('status', '状态', 'int', false);// 不传默认读取操作，默认0=关闭/1=开启

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            // 操作类型 默认0=读取，1=写入
            $operateType = 0;
            if (isset($this->requestData['status']) and is_numeric($this->requestData['status'])) {
                $operateType = 1;
            }

            $status = $this->requestData['status'] ?? 0;
            if (!in_array($status, [0, 1])) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = '动态审核开关状态不匹配';
                break;
            }

            $data['status'] = $this->trends->trendsAuditSwitch($operateType, $status);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 设置动态类型
     * */
    public function setTrendsType()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('content_id', '动态ID', 'int', true, '动态ID不能为空');
            $this->I('type', '类型', 'int', true, '类型不能为空');// 0=普通，1=精选，2=推荐

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            if (!in_array($this->requestData['type'], [0, 1, 2, 3])) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = '类型不匹配';
                break;
            }

            $ret = $this->trends->trendsUpdate($this->requestData['content_id'], ['type' => $this->requestData['type']]);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '动态' . Hint::getErrCodeMsg($code);
                break;
            }

            if ($this->requestData['type'] == 2) {
                $this->trends->trendsAddRecommend($this->requestData['content_id']);
            } else {
                $this->trends->trendsRemoveRecommend($this->requestData['content_id']);
            }

            $data['content_id'] = $this->requestData['content_id'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 动态审核
     * */
    public function trendsAudit()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('content_id', '动态ID', 'int', true, '动态ID不能为空');
            $this->I('state', '状态', 'int', true, '状态不能为空');// 0=待审核，1=已审核

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            if (!in_array($this->requestData['state'], [0, 1])) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = '状态不匹配';
                break;
            }

            $trendInfo = $this->trends->trend($this->requestData['content_id']);

            $trendUpdateData = ['state' => $this->requestData['state']];
            if ($trendInfo && $trendInfo['state'] == 0) {
                $trendUpdateData['status'] = 1;
            }

            if ($trendInfo && $trendInfo['state'] == 1) {
                $trendUpdateData['status'] = 2;
            }
            //同步到动态的作品审核通过不给粉丝发消息
            $data['is_send_message'] = 1;
            if($trendInfo['c_type'] == 6){
                $data['is_send_message'] = 0;
            }

            $ret = $this->trends->trendsUpdate($this->requestData['content_id'], $trendUpdateData);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '动态' . Hint::getErrCodeMsg($code);
                break;
            }

            // 若重新设置为待审核则表示该动态存在问题，从推荐列表缓存中移除
            if ($this->requestData['type'] == 0) {
                $this->trends->trendsRemoveRecommend($this->requestData['content_id']);
            }

            $data['content_id'] = $this->requestData['content_id'];
            $data['user_id'] = $trendInfo['user_id'];

        } while (false);

        return compact('code', 'msg', 'data');
    }


    /**
     * 获取动态点赞列表
     *
     * @param array $list 动态列表
     * @return array
     * */
    public function trendsLikeList()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('content_id', '动态ID', 'int', true, '动态ID不能为空');
            $this->I('page_index', 'page_index', 'int', false, '动态ID不能为空');
            $this->I('page_size', 'page_size', 'int', false, '动态ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $uids = [];
            $content_id = $this->requestData['content_id'];
            $page_index = $this->requestData['page_index'];
            $page_size = $this->requestData['page_size'];

            //获取点赞列表
            $list = $this->trends->getTrendLikeList($content_id, $page_index, $page_size);
            $listCount = $this->trends->getTrendLikeCount($content_id);

            //获取用户头像信息
            $uids = $list ? array_column($list, "user_id") : [];
            $users = $this->user->get_users_by_ids($uids);

            //处理用户头像信息
            foreach ($list as $lk => $lv) {
                $user_id = $lv['user_id'];
                $findUser = array_values(array_filter($users, function ($param) use ($user_id) {
                    return $param['user_id'] == $user_id;
                }));
                $list[$lk]['thumbnails'] = ($findUser && isset($findUser[0]) && isset($findUser[0]["thumbnails"]) && isset($findUser[0]["thumbnails"][0])) ? $findUser[0]["thumbnails"][0] : "";
                $list[$lk]['nickname'] = ($findUser && isset($findUser[0]) && isset($findUser[0]["nickname"])) ? $findUser[0]["nickname"] : "";
            }

            $data['list'] = $list;
            $data['page_index'] = $page_index;
            $data['page_count'] = ceil($listCount/$page_size);
            $data['page_size'] = intval($page_size);

        } while (false);

        return compact('code', 'msg', 'data');
    }


    public function cleanUserTrends($userIdArr)
    {
        DB::beginTransaction();
        foreach ($userIdArr as $userId){
            $this->trends->cleanUserTrends($userId);
        }
        DB::commit();
    }


    /**
     * 获取动态评论内容检测列表
     *
     * @param array $list 动态列表
     * @param int $type 1 - 评论 2 - 回复
     * @return array
     * */
    public function getContentCheckList($list, $type = 1)
    {
        do {
            if (empty($list)) {
                break;
            }
            $commentIds = [];
            $contentIds = [];

            //获取评论列表
            foreach ($list as $key => $value) {
                if ($type == 1) {
                    $commentIds = ($value['comment_list']) ? array_merge($commentIds, array_column($value['comment_list'], "comment_id")) : array_merge($commentIds, []);
                }
                if ($type == 2){
                    $commentIds = ($value['comment_list']) ? array_merge($commentIds, array_column($value['comment_list'], "reply_id")) : array_merge($commentIds, []);
                }
                $contentIds[] = $value['content_id'];
            }

            $commentIds = array_values(array_unique($commentIds));

            //获取用户审核数据
            $hideCommentIds = [];
            $currentUser = $this->user->get_current_user();
            if ($currentUser) {
                $contentCheckList = $this->contentCheckModel->getContentCheckListByDataIds($commentIds, [11, 12]);
                if ($contentCheckList) {
                    $hideCommentIds = array_column($contentCheckList, "data_id");
                }
            }
            $contentCheckGroupList = $this->contentCheckModel->getContentCheckListByContentIds($contentIds, [11, 12]);
            //获取评论列表用户信息
            foreach ($list as $key => $value) {
                if ($list[$key]['comment_list']) {
                    foreach ($list[$key]['comment_list'] as $lk => $lv) {
                        $comment_id = 0;

                        if ($type == 1) {
                            $comment_id = $lv['comment_id'];
                        }

                        if ($type == 2){
                            $comment_id = $lv['reply_id'];
                        }

                        $user_id = $lv['user_id'] ? $lv['user_id'] : $lv['from_user_id'];
                        if (in_array($comment_id, $hideCommentIds) && $currentUser['user_id'] != $user_id) {
                            unset($list[$key]['comment_list'][$lk]);
                        }
                    }
                    $list[$key]['comment_list'] = array_merge($list[$key]['comment_list']);

                    //处理评论数是否正确
                    $contentId = $value['content_id'];
                    $findContentCheck = array_values(array_filter($contentCheckGroupList, function ($param) use ($contentId) {
                        return $param['content_id'] == $contentId;
                    }));

                    if ($findContentCheck && $findContentCheck[0] ) {
                        $list[$key]['comment_count'] = $list[$key]['comment_count'] - $findContentCheck[0]['total'];
                    }
                }

            }

        } while (false);
        return $list;
    }

    /**后台删除 推荐广告位
     * @return array
     */
    public function greet(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('user_id', '用户id', 'int', true, '用户id不能为空');
            $this->I('trend_id', '动态ID', 'int', true, '动态ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $user_ids = $this->trends->getGreetUser($this->requestData['trend_id']);
            if(in_array($this->requestData['user_id'] , $user_ids)){
                $code = Hint::ERR_FAIL;
                $msg = '已经向TA打过招呼了，快去消息页面继续聊吧~';
                break;
            }
            $this->trends->setGreetUser($this->requestData['trend_id'] ,$this->requestData['user_id']);

        } while (false);

        return compact('code', 'msg', 'data');
    }
    /**后台增加/修改 推荐广告位
     * @return array
     */
    public function curdTrendsAd(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', '动态广告ID', 'int', false, '动态广告ID不能为空');
            $this->I('type', '类型', 'int', true, '类型不能为空');
            $this->I('target_id', '目标id', 'int', false, '目标id不能为空');
            $this->I('status', '状态', 'int', true, '状态不能为空');
            $this->I('title', '标题', 'string', true, '标题不能为空');
            $this->I('image', 'banner', 'string', false, 'banner不能为空');
            $this->I('url', '跳转链接', 'string', false, '跳转链接不能为空');
            $this->I('label', '标签', 'string', true, '标签不能为空');
            $this->I('start_timestamp', 'start_timestamp开始时间', 'string', true, '开始时间不能为空');
            $this->I('end_timestamp', 'end_timestamp结束时间', 'string', true, '结束时间不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $data =  $this->trends->curdTrendsAd(!empty($this->requestData['id']) ? 'update' : 'insert' ,$this->requestData);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**后台删除 推荐广告位
     * @return array
     */
    public function delTrendsAd(){
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', '动态广告ID', 'int', false, '动态广告ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            $data =  $this->trends->curdTrendsAd('del' ,$this->requestData);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    public function listFamily($page, $page_size ,$user_ids)
    {
        $list = $this->trends->trends_family_list($page ,$page_size ,$user_ids,true);

        $list = $this->trendsTopic($list);
        $list = $this->makeUserInfo($list ,true);
        $list = $this->countData($list);
        $list = $this->make_like($list);

        $list = $this->getTrendCommentList($list);

        //获取点赞列表
        $list = $this->getTrendLikeList($list);

        //处理审核内容相关
        $list = $this->getContentCheckList($list);

        return ['list' => $list, 'page_index' => $page, 'page_count' => count($list), 'page_size' => $page_size ];
    }

    /**
     * 最近动态
     */
    public function latelyTrends(int $userId) {
        return $this->trends->latelyTrends($userId, ['content_id', 'c_imgs']);
    }

    /**
     * 注册默认发送动态
     */
    public function registerTrend($user_id){
        $msg = '哟呼，新人报道，快来和我互动，一起开心撩聊！';
        $content = [
            [
                'type' => 0,
                'mess' => $msg,
            ]
        ];
        $releaseData = [
            'c_type' => 1,
            'm_type' => 2,
            'user_id' => $user_id,
            'c_content' => json_encode($content),
            'create_timestamp' => time(),
            'position_name' => '未知',
            'p_lng' => 0,
            'p_lat' => 0,
            'type' =>3,//默认所有人可见
            'long_img' => 0,
            'gender_type' => 1,
            'state' => 1,
            'status' => 1,
        ];
        $this->trends->trends_add($releaseData);
    }
}
